package com.liuyang.concurrency.chapter9;

import java.util.concurrent.locks.Lock;
import java.util.stream.Stream;

public class ProduceConsumerVersion2 {

    private int i = 0;

    final private Object LOCK = new Object();

    private volatile boolean isProduce = false;

    private void produce() {
        synchronized (LOCK) {
            if (isProduce) {
                System.out.println("P try wait");
                try {
                    LOCK.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();

                }
            } else {
                i++;
                System.out.println("P->" + Thread.currentThread().getName() + "|" + i);
                LOCK.notify();
                isProduce = true;
            }
        }
    }

    private void consume() {
        synchronized (LOCK) {
            if (isProduce) {
                System.out.println("C->" + Thread.currentThread().getName() + "|" + i);
                LOCK.notify();
                isProduce = false;
            } else {
                System.out.println("C try wait");
                try {
                    LOCK.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        ProduceConsumerVersion2 p = new ProduceConsumerVersion2();
        Stream.of("P1", "P2").forEach(n ->
                new Thread() {
                    @Override
                    public void run() {
                        while (true) {
                            System.out.println("Producer"+p.isProduce);
                            p.produce();
                        }
                    }
                }.start());

        Stream.of("C1", "C2").forEach(n ->
                new Thread() {
                    @Override
                    public void run() {
                        while (true) {
                            System.out.println("Consumer"+p.isProduce);
                            p.consume();
                        }
                    }
                }.start());
    }


}
